package contrallor;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/authorInfo")

public class AuthorServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过这个方法获取到指定的作者信息
        resp.setContentType("application/json;charset=utf8");
     String param = req.getParameter("blogId");
     if(param==null||"".equals(param)){
         //参数缺少
         resp.getWriter().write("{\"ok\":false,\"reason\":\"参数缺失\"}");
         return;
     }
     //根据当前的blogId在数据库中查找对应的blog对象,再进一步根据blog对象查找用户信息.
        BlogDao blogDao=new BlogDao();
        Blog blog=blogDao.selectOne(Integer.parseInt(param));
        if(blog==null){
            //参数缺少
            resp.getWriter().write("{\"ok\":false,\"reason\":\"要查询的博客不存在\"}");
            return;
        }
        //根据 blog 对象,查询到用户对象
        UserDao userDao = new UserDao();
        User author = userDao.selectById(blog.getUserId());
        if(author==null){
            resp.getWriter().write("{\"ok\":false,\"reason\":\"要查询的用户不存在\"}");
            return;
        }
        //把author 对象返回大浏览器这边
        //注意把密码不要返回给客户端
        author.setPassword("");
        resp.getWriter().write(objectMapper.writeValueAsString(author));
    }
}
